package service

import (
	"gocode/customerManage/model"
)

// 该结构体完成对customer的操作。包括增删改查
type CustomerService struct {
	customers []model.Customer
	// 声明一个字段表示当前切片含有多少客户
	// 还可以表示新用户：id+1
	customerNum int
}

// 编写一个方法返回一个customerService类型
func NewCustomerService() *CustomerService {
	// 为了能够看到有客户在切片中，我们初始化一个客户
	customerService := &CustomerService {}
	customerService.customerNum = 1
	customer := model.NewCustomer(1,"张三","男",20,"80088208","zs@sohu.com")
	customerService.customers = append(customerService.customers,customer)
	return customerService
}

// 返回客户切片
func (this *CustomerService) List() []model.Customer {
	return this.customers
}

// 往切片添加用户
func (this *CustomerService) Add(customer model.Customer) bool {
	// 我们确定一个分配id的规则，就是添加的顺序
	this.customerNum ++
	customer.Id = this.customerNum
	this.customers = append(this.customers,customer)
	return true
}

// 根据id查找客户在切片中对应下标，如果没有该客户返回 -1
func (this *CustomerService) FindId(id int) int {
 
	// 遍历
	index := -1
	for i,v:=range this.customers {
		if v.Id == id {
        index = i
		}
	}
	return index
}

// 根据id删除切片中的客户
func (this *CustomerService) Delete(id int) bool {
  index := this.FindId(id)
	// 如果index == -1 ,说明没有这个客户
	if index == -1 {
		return false
	}
	this.customers = append(this.customers[:index],this.customers[index+1:]...)
	return true
}

// 根据id修改切片中的客户
func (this *CustomerService) Update(customer model.Customer) bool {
	this.customers = append(this.customers,customer)
	return true
}